"""
This module handles woods and trees.

Woods are areas where trees (sprites) are in 
a wood has a function to generate random trees in it
"""

if __name__ == "__main__":
    import sys
    sys.path.append("../lib")

import grid
import pygame
import random
import reshelper
import os
import area
import tupleVector as tv

class Wood (area.Area):
    
    #center in tile units
    def __init__(self, world, id=0, center=(0,0)):
        super (Wood, self).__init__(world.grid, "wood", id, center)
        self.world = world
        self.trees = []
        self.res_helper = reshelper.ResourceHelper(world)
        
    # clean me up, recode me nicer
    def generate_trees(self, percent_for_tree=25):
        
        #points = self.find_points_distance(no_trees, 2)
        points = self.find_points_distance(10, 2)
        print points
        for t in points:
            ##FIXME:
            if __name__ == "__main__":
                p = os.path.join ("..", "res", "gfx", "tree.tar.gz")
            else:
                p = os.path.join ("res", "gfx", "tree.tar.gz")
            res = reshelper.ResourceHelper(self.world).loadBuildingTar (p,t.rect.topleft)
            self.trees.append(TreeSprite (self._grid))
            position = tv.vSub (t.rect.topleft, res[1])
            self.trees[-1].depth = self.world.grid.get_tile_at_pixelpos(position).get_zdepth()
            #self.trees[-1].depth = res[1]
            img = res[0].convert()
            img.set_colorkey ((255,0,255))
            self.trees[-1].img = img
            self.trees[-1].rect.topleft = position
            
class TreeSprite (grid.Gridsprite):
    def __init__ (self, grid):
        super (TreeSprite, self).__init__(grid)
        self.img = None
        
    def draw (self, screen, optional_ignore=None):
        screen.blit (self.img, self._grid.g2s(self.rect.topleft))
        
    def __repr__(self):
        return "<Treesprite at"+str(self.rect.topleft)+">"

     



if __name__ == "__main__": 
    
    import world.system
    s = world.system.System()
    s.set_screen (800,600)
    g = grid.Pathfinding_Grid ((0,0), 100, 100, (20,20))
    w = Wood (g, 1, (10,10))
    w.area_grow(25)
    w.area_grow(25)
    w.area_grow(25)
    w.area_grow(25)
    w.generate_trees(25)
    g.print_tag_register()
    for i in w.trees:
        print i
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                running = False
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_ESCAPE:
                    running = False
        s.screen.fill ((120,120,120))
        for i in w.trees:
            i.draw(s.screen)
        pygame.display.flip()
    